package com.ihtry.controller;

import com.ihtry.pojo.Book;
import com.ihtry.service.BookService;
import com.ihtry.utils.Code;
import com.ihtry.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    /**
     * 添加图书
     */
    @PostMapping
    public Result addBook(@RequestBody Book book) {
        boolean flag = bookService.addBook(book);
        String msg = flag ? "添加成功" : "添加失败";
        return new Result(flag ? Code.ADD_OK : Code.ADD_ERR, msg, null);
    }

    /**
     * 删除图书
     */
    @DeleteMapping("/{id}")
    public Result deleteBook(@PathVariable Integer id) {
        boolean flag = bookService.deleteBook(id);
        String msg = flag ? "删除成功" : "删除失败";
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, msg, null);

    }

    /**
     * 修改图书
     */
    @PutMapping
    public Result updateBook(@RequestBody Book book) {
        boolean flag = bookService.updateBook(book);
        String msg = flag ? "修改成功" : "修改失败";
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, msg, null);
    }

    /**
     * 查询全部
     */
    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        String msg = bookList != null ? "查询成功" : "查询失败";
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        return new Result(code, msg, bookList);
    }

    /**
     * 通过id查询
     */
    @GetMapping("/{id}")
    public Result getBookById(@PathVariable Integer id) {
        Book book = bookService.getBookById(id);
        String msg = book != null ? "查询成功" : "查询失败";
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;

        return new Result(code, msg, book);
    }
}
